﻿using System;
using System.ComponentModel;
using LayeredArchitectureSample.DataTransferObjects;
using LayeredArchitectureSample.Infrastructure;
using LayeredArchitectureSample.Infrastructure.Services;
using LayeredArchitectureSample.ServiceContracts;

namespace LayeredArchitectureSample.ViewModel
{
    internal class NewLocationViewModel : INotifyPropertyChanged
    {
        private readonly IServiceOperationInvoker<IRemoteLocationRepository> _remoteRepository;
        private readonly IExceptionAwareServiceCodeRunner _codeRunner;

        private string _name;
        private LocationViewModel _newlyCreatedLocation;
        private readonly string _nameProperty;

        public NewLocationViewModel(
            IServiceOperationInvoker<IRemoteLocationRepository> remoteRepository,
            IExceptionAwareServiceCodeRunner codeRunner)
        {
            if (remoteRepository == null) throw new ArgumentNullException("remoteRepository");

            _remoteRepository = remoteRepository;
            _codeRunner = codeRunner;
            _nameProperty = Reflection.GetPropertyName(() => this.Name);
        }

        public System.String Name
        {
            get
            {
                return _name;
            }
            set
            {
                _name = value;

                EventRaiser.RaisePropertyChangedEvent(PropertyChanged, this, _nameProperty);
            }
        }

        public LocationViewModel GetNewlyCreatedLocation()
        {
            if (_newlyCreatedLocation != null)
            {
                return _newlyCreatedLocation;
            }

            throw new InvalidOperationException(/*TODO*/);
        }

        public bool CreatedNewLocation
        {
            get { return _newlyCreatedLocation != null; }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// 
        /// </summary>
        public void AddNewLocationToRepository()
        {
            _codeRunner.RunCode(
                () =>
                    {
                        LocationDto locationDto = _remoteRepository.Invoke(x => x.AddNewLocation(Name));

                        _newlyCreatedLocation = new LocationViewModel(locationDto.Id, locationDto.Name);
                    });
        }
    }
}